/**
*  
* @Function 打包工具类
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.utils    
* @FileName ZipUtil.java    
* @Date 2018年10月23日下午4:31:25
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/  
package com.py.credit.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import javax.servlet.http.HttpServletResponse;

import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;

/**
 * 
 * @Function 打包工具类
 * @ClassName ZipUtil
 * @Date 2018年10月23日 下午4:31:25
 * @Author Min DongXv
 * 
 */
public class ZipUtil {

	private static final int ZERO = 0;

	private static final int BUFFER_SIZE = 2048;

	private static final int NEGATIVE_NUM_1 = -1;

	private static final String NO_FILE = "未读取到文件";

	private ZipUtil() {
	}

	/**
	 *
	 * @Function 压缩包文件下载
	 * @FileName ZipUtil.java
	 * @MethodName zipDownload
	 * @param zipName
	 *            压缩包名称
	 * @param zipFile
	 *            压缩包文件
	 * @throws IOException 
	 * @Author Min DongXv
	 *
	 */
	public static RestServiceResult<Object> zipDownload(String zipName, HttpServletResponse response, String zipPath) throws IOException {
		RestServiceResult<Object> result = new RestServiceResult<>();
		byte[] buffer = new byte[BUFFER_SIZE];
		File zipFile = new File(zipPath);
		FileInputStream zipInput = null;
		// 下载
		try {
			zipInput = new FileInputStream(zipFile);
			OutputStream out = response.getOutputStream();
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition",
					"attachment; filename=" + URLEncoder.encode(zipName, "UTF-8") + ".zip");
			int len;
			while ((len = zipInput.read(buffer)) != NEGATIVE_NUM_1) {
				out.write(buffer, ZERO, len);
			}
		} catch (Exception e) {
			ExceptionLogger.error("ZipUtil#zipDownload", "下载异常", e);
			throw new ServiceException("文件下载异常");
		}finally {
			zipInput.close();
		}
		return result;
	}
}
